package com.win.interceptor;

import com.alibaba.fastjson.JSON;
import com.win.utils.JwtHelper;
import com.win.utils.Result;
import com.win.utils.ResultCodeEnum;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
@Slf4j
public class JwtTokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }
        String token = request.getHeader("token");
        log.info("开始jwt token校验：用户token为：{}",token);

        boolean res = JwtHelper.isExpiration(token);

        if (!res){
            //没过期，直接放行
            return true;
        }else {
            log.info("token过期！");
            Result result = Result.build(null, ResultCodeEnum.ILLEGAL_LOGIN);
            String resultJson = JSON.toJSONString(result);
            response.getWriter().write(resultJson);
            return false;
        }
    }
}
